package com.yfeng.goodjuhome.action;


import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yfeng.goodjuhome.model.User;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hsqldb.lib.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.yfeng.common.utils.BeanUtil;
import com.yfeng.common.utils.PageUtil;
import com.yfeng.common.utils.Util;
import com.yfeng.goodjuhome.model.Group;
import com.yfeng.goodjuhome.model.Permission;
import com.yfeng.goodjuhome.service.IPermissionService;
import com.yfeng.goodjuhome.service.IUserService;
@Controller("userAction")
@SessionAttributes("currUser")
public class UserAction {

	private static final Log log = LogFactory.getLog(UserAction.class);

	@Autowired
	@Qualifier("userService")
	private IUserService userService;
	
	

	//	@Autowired
	//	@Qualifier("groupService")
	//	private IGroupService groupService;

	@Autowired
	private PageUtil pageUtil;

	/**
	 * 定位到用户管理列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/admin/userListPage")
	public String toUserIndexPage(HttpServletRequest req, ModelMap model)
	throws Exception {
		// List userList = userService.getUsers();
//		String cond="";
//		String username = Util.getStr(req.getParameter("username"));
//		String groupid = Util.getStr(req.getParameter("groupid"));
//		User currUser=(User)req.getSession().getAttribute("currUser");
//		User user=(User)BeanUtil.getBean("user");
//		List permissionList=new ArrayList();
//		if(currUser.getType()==2){ //非管理员
//			groupid=currUser.getGroupid();
//			List temp=user.getPermissionByUserId(currUser.getId());
//			for(int i=0;i<temp.size();i++){
//				Map m=(Map)temp.get(i);
//				permissionList.add(m.get("link").toString());
//			}
//			cond=" and (t.uid='"+currUser.getId()+"' or t.id='"+currUser.getId()+"')";
//		}
////		if(!StringUtils.isEmpty(groupid))
////			cond=" and t.groupid='"+groupid+"'";
//		int pageSize, recordCount, pageCount = 0;
//		int page = (req.getParameter("page") == null || "".equals(req.getParameter("page")))  ? 1 : Integer.parseInt(req.getParameter("page"));
//		page = page == 0 ? 1 : page;
//
//		pageSize = pageUtil.getPageSize(); // 一页显示多少条记录
//		recordCount = pageUtil
//		.getRecordCount("select count(*) from users t,groups t1 where t.groupid=t1.id and t.username like '%"+username+"%' "+cond);
//		pageCount = pageUtil.getPageCount(recordCount);// 取有多少页
//
//		List userList = pageUtil.query(page,
//				"t.*,t1.name",
//				"users t,groups t1",
//				" and t.groupid=t1.id and t.username like '%"+username+"%' "+cond+" ","order by t.id asc");
//		String pageHtml = pageUtil.printHtml(page, recordCount, pageCount,"&username="+username+"&groupid="+groupid);
//		model.addAttribute("pageHtml", pageHtml);
//		model.addAttribute("username",username);
//		model.addAttribute("userList",userList);
//		model.addAttribute("permissionList",permissionList);
//		model.addAttribute("isAdmin",currUser.getType());
		return "/admin/user/userList";
	}

	/**
	 * 新增用户界面
	 * 
	 * @return
	 */
	@RequestMapping("/admin/adduser_page")
	public String toUserAddPage(HttpServletRequest req,ModelMap model) {
		try
		{
//			Group group = (Group) BeanUtil.getBean("group");
//			User currUser=(User)req.getSession().getAttribute("currUser");
//			if(currUser.getType()==2){
//				model.addAttribute("groupList", group.getGroupsByUserId(String.valueOf(currUser.getId())));
//			}else{
//				model.addAttribute("groupList", group.getGroups());
//			}
//			model.addAttribute("method","add");
			return "/admin/user/userEdit";
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}
		/**
		 * 添加用户
		 * @param req
		 * @param res
		 * @param session
		 * @throws Exception
		 */
		@RequestMapping("/admin/adduser")
		public void addUser(HttpServletRequest req, HttpServletResponse res,HttpSession session)
				throws Exception {
			User currUser=(User)session.getAttribute("currUser");
			String method=req.getParameter("method");
			String username = req.getParameter("username");
			String passwd = req.getParameter("passwd");
			String point = req.getParameter("point");
			String groupid = req.getParameter("groupid");
			String uid=req.getParameter("uid");
			String type=req.getParameter("type");
			int i=0;
			req.setCharacterEncoding("UTF-8");
			res.setContentType("text/html;charset=UTF-8");
			PrintWriter write = res.getWriter();
			if(method.equals("add")){
//				i=userService.addUser(username, passwd, groupid,point,type,String.valueOf(currUser.getId()));
//				if(i==-1){
//					write.print("<script>alert('保存失败,可能有重复的用户名！');history.back();</script>");
//				}else if(i>0){
//					write.print("<script>alert('用户添加成功');window.location='"
//							+ req.getContextPath()
//							+ "/admin/userListPage.do';</script>");
//				}else{
//					write.print("<script>alert('保存失败！');history.back();</script>");
//				}
			}else{
				i=userService.modUser(uid, passwd, groupid,point,type);
				if(i>0){
					write.print("<script>alert('用户修改成功');window.location='"
							+ req.getContextPath()
							+ "/admin/userListPage.do';</script>");
				}else{
					write.print("<script>alert('修改失败！');history.back();</script>");
				}
			}
		}
		/**
		 * 导航到修改用户信息页面
		 * @param req
		 * @param res
		 * @param model
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/admin/moduser_page")
		public String toUserModPage(HttpServletRequest req,
				HttpServletResponse res, ModelMap model) throws Exception {

			String id = req.getParameter("id");
			req.setCharacterEncoding("UTF-8");
			res.setContentType("text/html;charset=UTF-8");
			PrintWriter write = res.getWriter();
			if (!StringUtils.isEmpty(id)) {
				Group group = (Group) BeanUtil.getBean("group");
				User user = (User) BeanUtil.getBean("user");
				User currUser=(User)req.getSession().getAttribute("currUser");
//				if(currUser.getType()==2){
//					model.addAttribute("groupList", group.getGroupsByUserId(String.valueOf(currUser.getId())));
//				}else{
//					model.addAttribute("groupList", group.getGroups());
//				}
				model.addAttribute("user", user.getUserById(id));
				model.addAttribute("method", "mod");
			}
			return "/admin/user/userEdit";

		}
	/*
	 * 删除用户
	 */
	@RequestMapping("/admin/deluser")
	public void delUser(HttpServletRequest req, HttpServletResponse res)
	throws Exception {

		String[] ids = req.getParameterValues("id");
		String method=req.getParameter("method");
		req.setCharacterEncoding("UTF-8");
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter write = res.getWriter();
		int ret = userService.deleteUser(ids,method);
		if (ret==2)
			write.print("<script>alert('用户已删除!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");
		else if (ret==3)
			write.print("<script>alert('用户已解锁!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");
		else if (ret==1)
			write.print("<script>alert('用户已锁定!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");
		else if(ret==0 && method.equals("del"))
			write.print("<script>alert('删除出错,可能没有选中用户!');history.back();</script>");
		else if(ret==0 && method.equals("lock"))
			write.print("<script>alert('锁定出错,可能没有选中用户!');history.back();</script>");
		else if(ret==0 && method.equals("unlock"))
			write.print("<script>alert('解锁出错,可能没有选中用户!');history.back();</script>");
		else if(ret==-1)
			write.print("<script>alert('删除出错，不能删除所有管理员!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");

	}
	
	@RequestMapping("/admin/toSetPermissionPage")
	public String toSetPermissionPage(HttpServletRequest req, ModelMap model)throws Exception{
//		String userid = Util.getStr(req.getParameter("id"));
//
//		String name = Util.getStr(req.getParameter("name"));
//		User user=(User)BeanUtil.getBean("user");
//		User currUser=(User)req.getSession().getAttribute("currUser");
//
//		List pidList=null;
//		if(!StringUtil.isEmpty(userid)){
//			pidList=userService.getPermissionIdsByUser(userid);
//		}else{
//			userid=Util.getStr(req.getParameter("userid"));
//			if(!StringUtil.isEmpty(userid)){
//				pidList=userService.getPermissionIdsByUser(userid);
//			}
//		}
//		int pageSize,recordCount, pageCount = 0;
//		int page = (req.getParameter("page") == null || "".equals(req.getParameter("page")))  ? 1 : Integer.parseInt(req.getParameter("page"));
//		page = page == 0 ? 1 : page;
//
//		pageSize = pageUtil.getPageSize(); // 一页显示多少条记录
//		if(currUser.getType()==2){ //非管理员
//			recordCount = pageUtil.getRecordCount("select count(*) from permissions t,user_permission t1 where t.name like '%"+name+"%' and t1.uid='"+currUser.getId()+"' and t1.pid=t.id");
//		}else{
//			recordCount = pageUtil.getRecordCount("select count(*) from permissions t where t.name like '%"+name+"%'");
//		}
//		pageCount = pageUtil.getPageCount(recordCount);// 取有多少页
//
//		List permissionList = null;
//		if(currUser.getType()==2){
//			permissionList=pageUtil.query(page,
//					"t.*",
//					" permissions t,user_permission t1 ",
//					" and t.name like '%"+name+"%' and t1.uid='"+currUser.getId()+"' and t1.pid=t.id ",
//			" order by t.id desc");
//		}else{
//			permissionList=pageUtil.query(page,
//					"t.*",
//					" permissions t",
//					" and t.name like '%"+name+"%'",
//			" order by t.id desc");
//		}
//
//		String pageHtml = pageUtil.printHtml(page, recordCount, pageCount,"&name="+name+"&userid="+userid);
//
//		model.addAttribute("pageHtml", pageHtml);
//		model.addAttribute("name",name);
//		model.addAttribute("permissionList",permissionList);
//		model.addAttribute("pidList",pidList);
//		model.addAttribute("userid",userid);
//		model.addAttribute("currPage",Integer.valueOf(page).toString());
		return "/admin/user/setPermission";
	}
	
	@RequestMapping("/admin/setPermission")
	public void setPermission(HttpServletRequest req, HttpServletResponse res)
	throws Exception {

		String[] ids = req.getParameterValues("id");
		req.setCharacterEncoding("UTF-8");
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter write = res.getWriter();
		int ret;
		String userid=Util.getEmptyStr(req.getParameter("userid"));
		int page=Integer.valueOf(req.getParameter("page"));
		String name=Util.getEmptyStr(req.getParameter("name"));
		List permissionList = pageUtil.query(page,
				"t.*",
				" permissions t",
				" and t.name like '%"+name+"%'",
		" order by t.id desc");
		ret=3;
		if(ret==1){
			write.print("<script>alert('权限分配成功!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");
		}else if(ret==-1){
			write.print("<script>alert('权限分配失败!');window.location='"+ req.getContextPath()+ "/admin/userListPage.do';</script>");
		}

	}
	
	
	@RequestMapping("/admin/permissionListPage")
	public String toPermissionIndexPage(HttpServletRequest req, ModelMap model)
	throws Exception {
		// List userList = userService.getUsers();
		String name = Util.getEmptyStr(req.getParameter("name"));
		String userid=Util.getEmptyStr(req.getParameter("userid"));
		User user=(User)BeanUtil.getBean("user");
		User checkUser=null;
		List pidList=null;
		if(!StringUtil.isEmpty(userid)){
			checkUser=user.getUserById(userid);
			//pidList=userService.getPermissionIdsByUser(userid);
		}
		int pageSize, recordCount, pageCount = 0;
		int page = (req.getParameter("page") == null || "".equals(req.getParameter("page")))  ? 1 : Integer.parseInt(req.getParameter("page"));
		page = page == 0 ? 1 : page;

		pageSize = pageUtil.getPageSize(); // 一页显示多少条记录
		recordCount = pageUtil
		.getRecordCount("select count(*) from permissions t where t.name like '%"+name+"%'");
		pageCount = pageUtil.getPageCount(recordCount);// 取有多少页

		List permissionList = pageUtil.query(page,
				"t.*",
				" permissions t",
				" and t.name like '%"+name+"%'",
				" order by t.id desc");
		String pageHtml = pageUtil.printHtml(page, recordCount, pageCount,"&name="+name);
		
		
		List userList=null;
		model.addAttribute("pageHtml", pageHtml);
		model.addAttribute("name",name);
		model.addAttribute("permissionList",permissionList);
		model.addAttribute("userList",userList);
		model.addAttribute("user",checkUser);
		model.addAttribute("pidList",pidList);
		return "/admin/user/permissionList";
	}

		


}